﻿using DataTransfer.Core.Configurations;
using DataTransfer.Core.Domains;
using DataTransfer.SDK.Models;
using MiniFox.Components;
using MiniFox.Configurations;

namespace DataTransfer.Core.Providers
{
    /// <summary>
    /// 
    /// </summary>
    [AutoRegister, SpareComponent(typeof(ImportConfigProvider))]
    public interface IImportConfigProvider
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        IImporter GetImporter(string name);
    }

    internal class ImportConfigProvider : IImportConfigProvider
    {
        public IImporter GetImporter(string name)
        {
            var settings = ConfigurationFactory.GetConfig<ExcelImportSettingCollection>();
            var setting = settings[name];
            return new ExcelImporter
            {
                Name = setting.Name,
                DataWriterTypeName = setting.DataWriterTypeName,
                MaxImportFileSize = setting.MaxImportFileSize,
                PreImport = setting.PreImport,
                Modules = new Dictionary<string, Type>(setting.Modules.Select(p => new KeyValuePair<string, Type>(p.Name, p))),
                Sheets = setting.Sheets.Select(s => new ExcelImportSheet
                {
                    SheetName = s.SheetName,
                    OperateName = s.OperateName,
                    StartRowIndex = s.StartRowIndex,
                    HeaderRowIndex = s.HeaderRowIndex,
                    Fields = s.Fields.Select(f => new ExcelImportSheetField
                    {
                        FieldName = f.FieldName,
                        DisplayName = f.DisplayName,
                        Ordinal = f.Ordinal,
                        MissingCellPolicy = f.MissingCellPolicy,
                        TypeName = f.FieldType
                    }).ToArray()
                })
            };
        }
    }
}
